package modbus_client

import (
	"backend/internal/core/types"
	"context"
	"encoding/binary"
	"errors"
	"fmt"
	"github.com/goburrow/modbus"
	"github.com/zeromicro/go-zero/core/logx"
	"log"
	"math"
	"strings"
	"sync"
	"time"
)

// packValue 根据字节序和值进行打包
// packValue 根据字节序和值进行打包
func packValue(byteorder types.ByteOrder, value interface{}) []byte {
	var floatValue float64

	// 将输入值转换为 float64
	switch v := value.(type) {
	case int:
		floatValue = float64(v)
	case int8:
		floatValue = float64(v)
	case int16:
		floatValue = float64(v)
	case int32:
		floatValue = float64(v)
	case int64:
		floatValue = float64(v)
	case uint:
		floatValue = float64(v)
	case uint8:
		floatValue = float64(v)
	case uint16:
		floatValue = float64(v)
	case uint32:
		floatValue = float64(v)
	case uint64:
		floatValue = float64(v)
	case float32:
		floatValue = float64(v)
	case float64:
		floatValue = v
	default:
		logx.Errorf("Unsupported data type: %T", value)
		return nil
	}

	var buf []byte
	switch byteorder {
	case types.BigEndUnsignedShort, types.BigEndSignedShort:
		buf = make([]byte, 2)
		// 截断为 uint16 类型
		binary.BigEndian.PutUint16(buf, uint16(floatValue))
	case types.BigEndSignedInt:
		buf = make([]byte, 4)
		binary.BigEndian.PutUint32(buf, uint32(floatValue))
	case types.LittleEndSignedInt:
		buf = make([]byte, 4)
		binary.LittleEndian.PutUint32(buf, uint32(floatValue))
	case types.BigEndWordSwappedSignedInt:
		buf = make([]byte, 4)
		binary.BigEndian.PutUint32(buf, uint32(floatValue))
		// 交换字节序（按 16 位字交换）
		buf[0], buf[2] = buf[2], buf[0]
		buf[1], buf[3] = buf[3], buf[1]
	case types.LittleEndWordSwappedSignedInt:
		buf = make([]byte, 4)
		binary.LittleEndian.PutUint32(buf, uint32(floatValue))
		// 交换字节序（按 16 位字交换）
		buf[0], buf[2] = buf[2], buf[0]
		buf[1], buf[3] = buf[3], buf[1]
	case types.BigEndFloat:
		buf = make([]byte, 4)
		bits := math.Float32bits(float32(floatValue))
		binary.BigEndian.PutUint32(buf, bits)
	case types.LittleEndFloat:
		buf = make([]byte, 4)
		bits := math.Float32bits(float32(floatValue))
		binary.LittleEndian.PutUint32(buf, bits)
	case types.WordSwappedFloat:
		buf = make([]byte, 4)
		bits := math.Float32bits(float32(floatValue))
		binary.BigEndian.PutUint32(buf, bits)
		// 交换字节序（按 16 位字交换）
		buf[0], buf[2] = buf[2], buf[0]
		buf[1], buf[3] = buf[3], buf[1]
	case types.LittleEndWordSwappedFloat:
		buf = make([]byte, 4)
		bits := math.Float32bits(float32(floatValue))
		binary.LittleEndian.PutUint32(buf, bits)
		// 交换字节序（按 16 位字交换）
		buf[0], buf[2] = buf[2], buf[0]
		buf[1], buf[3] = buf[3], buf[1]
	default:
		logx.Errorf("Unsupported byte order: %v", byteorder)
		return nil
	}
	return buf
}

// intsToBytes 将 uint16 切片转换为字节切片
func intsToBytes(ints []uint16) []byte {
	byteLen := len(ints) * 2
	bytes := make([]byte, byteLen)
	for i, v := range ints {
		pos := i * 2
		bytes[pos] = byte(v >> 8)
		bytes[pos+1] = byte(v)
	}
	return bytes
}

type logxAdapter struct{}

func (l *logxAdapter) Write(p []byte) (n int, err error) {
	// 将标准日志输出重定向到logx
	logx.Info(string(p)) // 或根据内容判断级别（如包含"error"时用logx.Error）
	return len(p), nil
}

// ModbusClient Modbus 客户端结构体
type ModbusClient struct {
	mu           sync.Mutex
	ProtocolType types.ProtocolType
	Client       modbus.Client
	Handler      modbus.ClientHandler
	Connected    bool          // 连接状态
	messageQueue *MessageQueue // 消息队列
}

// modbusLogger 自定义 Modbus 日志记录器，用于捕获原始报文
type modbusLogger struct {
	messageQueue *MessageQueue
}

// 实现 io.Writer 接口，用于将日志信息写入消息队列
func (l *modbusLogger) Write(p []byte) (n int, err error) {
	logMsg := string(p)
	// 去除日志信息末尾的换行符
	logMsg = strings.TrimSpace(logMsg)
	// 获取当前时间并格式化
	currentTime := time.Now().Format("2006-01-02 15:04:05.000")

	// 检查是否为发送消息
	if strings.Contains(logMsg, "modbus: sending") {
		sendingMsg := strings.TrimPrefix(logMsg, "modbus: sending ")
		l.messageQueue.Enqueue(fmt.Sprintf("[%s] TX: %s", currentTime, sendingMsg))
	} else if strings.Contains(logMsg, "modbus: received") { // 检查是否为接收消息
		receivedMsg := strings.TrimPrefix(logMsg, "modbus: received ")
		l.messageQueue.Enqueue(fmt.Sprintf("[%s] RX: %s", currentTime, receivedMsg))
	}
	return len(p), nil
}

// NewModbusClient 创建 Modbus 客户端实例
func NewModbusClient(protocolType types.ProtocolType, tcpConfig *types.TcpConfig, rtuConfig *types.RtuConfig) *ModbusClient {
	// 使用 new 关键字创建 ModbusClient 类型的指针
	client := new(ModbusClient)
	client.ProtocolType = protocolType
	client.Connected = false
	client.messageQueue = NewMessageQueue(1000) // 初始化消息队列，最大长度 1000

	// 创建自定义日志记录器
	customLogger := &modbusLogger{
		messageQueue: client.messageQueue,
	}
	// 使用 log.New 创建 *log.Logger 实例，将自定义日志记录器作为 io.Writer
	logger := log.New(customLogger, "", 0)

	switch protocolType {
	case types.Tcp, types.RtuOverTcp:
		client.setTcpClient(tcpConfig, logger)
	case types.Rtu:
		client.setRtuClient(rtuConfig, logger)
	}
	// 直接返回 client 指针
	return client
}

// setTcpClient 设置 Tcp 客户端
func (c *ModbusClient) setTcpClient(tcpConfig *types.TcpConfig, logger *log.Logger) {
	switch tcpConfig.ProtocolType {
	case types.Tcp:
		handler := modbus.NewTCPClientHandler(fmt.Sprintf("%s:%d", tcpConfig.Host, tcpConfig.Port))
		handler.SlaveId = 1
		handler.Timeout = 3 * time.Second
		handler.Logger = logger // 设置自定义日志记录器
		c.Client = modbus.NewClient(handler)
		c.Handler = handler
	case types.RtuOverTcp:
		handler := modbus.NewRTUClientHandler(fmt.Sprintf("%s:%d", tcpConfig.Host, tcpConfig.Port))
		handler.SlaveId = 1
		handler.Timeout = 3 * time.Second
		handler.Logger = logger
		c.Client = modbus.NewClient(handler)
		c.Handler = handler
	default:
		panic("unhandled default case")
	}
}

// setRtuClient 设置 Rtu 客户端
func (c *ModbusClient) setRtuClient(rtuConfig *types.RtuConfig, logger *log.Logger) {
	handler := modbus.NewRTUClientHandler(rtuConfig.Port)
	handler.BaudRate = int(rtuConfig.Baudrate)
	handler.DataBits = int(rtuConfig.Bytesize)
	handler.Parity = rtuConfig.Parity
	handler.StopBits = int(rtuConfig.Stopbits)
	handler.SlaveId = 1
	handler.Timeout = 3 * time.Second
	handler.Logger = logger
	c.Client = modbus.NewClient(handler)
	c.Handler = handler
}

// Connect 连接到 Modbus 服务器
func (c *ModbusClient) Connect() bool {
	logx.Debugf("Attempting to connect to Modbus server")

	// 使用互斥锁保证并发安全
	c.mu.Lock()
	defer c.mu.Unlock()

	// 检查 handler 是否为 nil
	if c.Handler == nil {
		logx.Errorf("Modbus client handler is nil, cannot connect")
		return false
	}

	if c.Connected {
		logx.Infof("Already Connected to Modbus server")
		return true
	}

	// 尝试进行类型断言，调用 Connect 方法
	if connector, ok := c.Handler.(interface{ Connect() error }); ok {
		// 设置连接超时
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()

		errChan := make(chan error, 1)
		go func() {
			errChan <- connector.Connect()
		}()

		select {
		case err := <-errChan:
			if err != nil {
				logx.Errorf("Failed to connect to Modbus server: %v", err)
				return false
			}
			c.Connected = true
		case <-ctx.Done():
			logx.Errorf("Connect operation timed out")
			return false
		}
	} else {
		logx.Errorf("Modbus client handler does not implement Connect method")
		return false
	}

	logx.Infof("Successfully Connected to Modbus server")
	return true
}

// Disconnect 断开与 Modbus 服务器的连接
func (c *ModbusClient) Disconnect() {
	// 使用互斥锁保证并发安全
	c.mu.Lock()
	defer c.mu.Unlock()

	// 检查 handler 是否为 nil
	if c.Handler == nil {
		logx.Errorf("Modbus client handler is nil, cannot disconnect")
		return
	}

	// 若已经断开连接，直接返回
	if !c.Connected {
		logx.Infof("Already disconnected from Modbus server")
		return
	}

	// 尝试进行类型断言，调用 Close 方法
	if closer, ok := c.Handler.(interface{ Close() error }); ok {
		// 设置断开连接超时
		ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
		defer cancel()

		errChan := make(chan error, 1)
		go func() {
			errChan <- closer.Close()
		}()

		select {
		case err := <-errChan:
			if err != nil {
				logx.Errorf("Failed to close Modbus connection: %v", err)
			}
		case <-ctx.Done():
			logx.Errorf("Disconnect operation timed out")
		}
	} else {
		logx.Errorf("Modbus client handler does not implement Close method")
	}

	// 更新连接状态
	c.Connected = false
	logx.Infof("Disconnected from Modbus server")
}

// SetSlaveID 动态设置从机地址
func (c *ModbusClient) SetSlaveID(slaveID uint8) {
	// 检查 handler 是否为 nil
	if c.Handler == nil {
		logx.Errorf("Modbus client handler is nil, cannot set slave ID")
		return
	}
	// 尝试将 handler 转换为具体实现类型的指针
	if tcpHandler, ok := c.Handler.(*modbus.TCPClientHandler); ok {
		tcpHandler.SlaveId = slaveID
		logx.Infof("Successfully set slave ID to %d", slaveID)
	} else if rtuHandler, ok := c.Handler.(*modbus.RTUClientHandler); ok {
		rtuHandler.SlaveId = slaveID
		logx.Infof("Successfully set slave ID to %d", slaveID)
	} else {
		logx.Errorf("Modbus client handler does not support setting slave ID")
	}
}

// ReadRegister 读取寄存器
func (c *ModbusClient) ReadRegister(slaveID uint8, registerType int32, startAddress, endAddress uint16) ([]int32, error) {
	// 检查连接状态，若未连接则尝试连接
	if !c.Connected {
		logx.Errorf("连接未打开, 无法读取寄存器")
		return nil, errors.New("连接未打开, 无法读取寄存器")
	}
	var valueList []int32
	count := endAddress - startAddress + 1
	switch types.RegisterType(registerType) {
	case types.Coil:
		valueList = c.ReadCoilRegisters(slaveID, startAddress, count)
	case types.DiscreteInput:
		valueList = c.ReadDiscreteInputRegisters(slaveID, startAddress, count)
	case types.HoldingRegister:
		valueList = c.ReadHoldingRegisters(slaveID, startAddress, count)
	case types.InputRegister:
		valueList = c.ReadInputRegisters(slaveID, startAddress, count)
	}
	return valueList, nil
}

// WriteRegister 根据寄存器类型和功能码写入寄存器
func (c *ModbusClient) WriteRegister(slaveID uint8, registerType types.RegisterType, startAddress uint16, writeFunc types.ModbusFunctionCode, dataType string, valueList []float32) (bool, error) {
	// 检查连接状态，若未连接则尝试连接
	if !c.Connected {
		logx.Errorf("连接未打开, 无法写入寄存器")
		return false, errors.New("连接未打开, 无法写入寄存器")
	}

	var isSuccess bool
	var err error

	switch registerType {
	case types.Coil:
		int32ValueList, err := convertToInt32List(valueList)
		if err != nil {
			logx.Errorf("转换值列表为 int32 类型失败: %v", err)
			return false, err
		}
		if writeFunc == types.WriteSingleCoilRegister {
			isSuccess = c.WriteSingleCoilRegister(slaveID, startAddress, int32ValueList)
		} else if writeFunc == types.WriteMultipleCoilRegisters {
			isSuccess = c.WriteMultipleCoilRegisters(slaveID, startAddress, int32ValueList)
		}
	case types.HoldingRegister:
		if writeFunc == types.WriteSingleHoldingRegister {
			isSuccess = c.WriteSingleHoldingRegisterFloat(slaveID, startAddress, dataType, valueList)
		} else if writeFunc == types.WriteMultipleHolingRegisters {
			isSuccess = c.WriteMultipleHoldingRegistersFloat(slaveID, startAddress, dataType, valueList)
		}
	default:
		errMsg := fmt.Sprintf("不支持的寄存器类型: %d", registerType)
		logx.Errorf(errMsg)
		return false, fmt.Errorf(errMsg)
	}

	return isSuccess, err
}

// convertToInt32List 将 []float32 转换为 []int32
func convertToInt32List(valueList []float32) ([]int32, error) {
	var int32List []int32
	for _, value := range valueList {
		int32List = append(int32List, int32(value))
	}
	return int32List, nil
}

// ReadCoilRegisters 读取线圈寄存器
func (c *ModbusClient) ReadCoilRegisters(slaveID uint8, address, count uint16) []int32 {
	const maxRegistersCnt = 1000
	var result []int32

	// 动态设置从机地址
	c.SetSlaveID(slaveID)

	for offset := uint16(0); offset < count; offset += maxRegistersCnt {
		batchSize := count - offset
		if batchSize > maxRegistersCnt {
			batchSize = maxRegistersCnt
		}
		currentAddress := address + offset

		// 移除 slaveID 参数
		resp, err := c.Client.ReadCoils(currentAddress, batchSize)
		if err != nil {
			logx.Errorf("读取线圈寄存器异常: %v", err)
			return nil
		}

		var batchResult []int32
		bitCount := 0
		for _, b := range resp {
			for i := 0; i < 8; i++ {
				if len(result) >= int(count) {
					break
				}
				var value int32
				if (b & (1 << uint(i))) != 0 {
					value = 1
				} else {
					value = 0
				}
				result = append(result, value)
				batchResult = append(batchResult, value)
				bitCount++
				if bitCount >= int(batchSize) {
					break
				}
			}
			if bitCount >= int(batchSize) {
				break
			}
		}
		logx.Infof("成功读取线圈寄存器: 从机%d 地址%d-%d，读取的值: %v", slaveID, currentAddress, currentAddress+batchSize-1, batchResult)
	}
	return result
}

// ReadDiscreteInputRegisters 读取离散输入寄存器
func (c *ModbusClient) ReadDiscreteInputRegisters(slaveID uint8, address uint16, count uint16) []int32 {
	const maxRegistersCnt = 1000
	var result []int32

	// 动态设置从机地址
	c.SetSlaveID(slaveID)

	for offset := uint16(0); offset < count; offset += maxRegistersCnt {
		batchSize := count - offset
		if batchSize > maxRegistersCnt {
			batchSize = maxRegistersCnt
		}
		currentAddress := address + offset

		logx.Infof("currentAddress: %v batchSize: %v", currentAddress, batchSize)
		resp, err := c.Client.ReadDiscreteInputs(currentAddress, batchSize)
		if err != nil {
			logx.Errorf("读取离散寄存器异常: %v", err)
			return nil
		}

		logx.Debugf("读取离散寄存器返回的原始值列表: %v", resp)

		var batchResult []int32
		bitCount := 0
		for _, b := range resp {
			for i := 0; i < 8; i++ {
				if len(result) >= int(count) {
					break
				}
				var value int32
				if (b & (1 << uint(i))) != 0 {
					value = 1
				} else {
					value = 0
				}
				result = append(result, value)
				batchResult = append(batchResult, value)
				bitCount++
				if bitCount >= int(batchSize) {
					break
				}
			}
			if bitCount >= int(batchSize) {
				break
			}
		}
		logx.Infof("成功读取离散输入寄存器: 从机%d 地址%d-%d，读取的值: %v", slaveID, currentAddress, currentAddress+batchSize-1, batchResult)
	}
	return result
}

// ReadHoldingRegisters 读取保持寄存器
func (c *ModbusClient) ReadHoldingRegisters(slaveID uint8, address, count uint16) []int32 {
	const maxRegistersCnt = 125
	var result []int32

	// 动态设置从机地址
	c.SetSlaveID(slaveID)

	for offset := uint16(0); offset < count; offset += maxRegistersCnt {
		batchSize := count - offset
		if batchSize > maxRegistersCnt {
			batchSize = maxRegistersCnt
		}
		currentAddress := address + offset

		resp, err := c.Client.ReadHoldingRegisters(currentAddress, batchSize)
		if err != nil {
			logx.Errorf("读取保持寄存器异常: %v", err)
			return nil
		}

		for i := 0; i < len(resp); i += 2 {
			value := int32(resp[i])<<8 | int32(resp[i+1])
			result = append(result, value)
		}
		logx.Infof("成功读取保持寄存器: 从机%d 地址%d-%d", slaveID, currentAddress, currentAddress+batchSize-1)
	}
	return result
}

// ReadInputRegisters 读取输入寄存器
func (c *ModbusClient) ReadInputRegisters(slaveID uint8, address, count uint16) []int32 {
	const maxRegistersCnt = 125
	var result []int32

	// 动态设置从机地址
	c.SetSlaveID(slaveID)

	for offset := uint16(0); offset < count; offset += maxRegistersCnt {
		batchSize := count - offset
		if batchSize > maxRegistersCnt {
			batchSize = maxRegistersCnt
		}
		currentAddress := address + offset

		resp, err := c.Client.ReadInputRegisters(currentAddress, batchSize)
		if err != nil {
			logx.Errorf("读取输入寄存器异常: %v", err)
			return nil
		}

		for i := 0; i < len(resp); i += 2 {
			value := int32(resp[i])<<8 | int32(resp[i+1])
			result = append(result, value)
		}
		logx.Infof("成功读取输入寄存器: 从机%d 地址%d-%d", slaveID, currentAddress, currentAddress+batchSize-1)
	}
	return result
}

// packValuesToRegisters 将值列表根据字节序打包为寄存器值列表
func packValuesToRegisters(byteorder types.ByteOrder, valueList []int32) ([]uint16, error) {
	var registers []uint16
	for _, value := range valueList {
		packed := packValue(byteorder, value)
		for i := 0; i < len(packed); i += 2 {
			if i+2 > len(packed) {
				return nil, fmt.Errorf("打包数据长度不是 2 的倍数")
			}
			chunk := packed[i : i+2]
			regValue := binary.BigEndian.Uint16(chunk)
			registers = append(registers, regValue)
		}
	}
	return registers, nil
}

// WriteSingleCoilRegister 写入单个线圈寄存器
func (c *ModbusClient) WriteSingleCoilRegister(slaveID uint8, startAddress uint16, valueList []int32) bool {
	// 动态设置从机地址
	c.SetSlaveID(slaveID)

	for index, value := range valueList {
		// 输入值验证
		if value != 0 && value != 1 {
			logx.Errorf("单个写入线圈寄存器时出错: 输入值 %d 无效，仅支持 0 和 1", value)
			return false
		}

		coilValue := convertToCoilValue(value)
		address := startAddress + uint16(index)
		_, err := c.Client.WriteSingleCoil(address, coilValue)
		if err != nil {
			logx.Errorf("单个写入线圈寄存器地址 %d 时出错: %v", address, err)
			return false
		}
	}
	logx.Infof("成功写入单个线圈寄存器: 从机%d 起始地址%d 数量%d", slaveID, startAddress, len(valueList))
	return true
}

// convertToCoilValue 将 int32 值转换为 Modbus 线圈寄存器所需的 uint16 值
func convertToCoilValue(value int32) uint16 {
	if value == 1 {
		return 0xFF00
	}
	return 0x0000
}

// WriteMultipleCoilRegisters 批量写入线圈寄存器（支持多寄存器）
func (c *ModbusClient) WriteMultipleCoilRegisters(slaveID uint8, startAddress uint16, valueList []int32) bool {
	// 动态设置从机地址
	c.SetSlaveID(slaveID)

	var byteValues []byte
	for i := 0; i < len(valueList); i += 8 {
		var b byte
		for j := 0; j < 8 && i+j < len(valueList); j++ {
			if valueList[i+j] == 1 {
				b |= 1 << uint(j)
			}
		}
		byteValues = append(byteValues, b)
	}

	_, err := c.Client.WriteMultipleCoils(startAddress, uint16(len(valueList)), byteValues)
	if err != nil {
		logx.Errorf("批量写入线圈寄存器时发生异常: %v", err)
		return false
	}
	logx.Infof("成功批量写入线圈寄存器: 从机%d 起始地址%d 数量%d", slaveID, startAddress, len(valueList))
	return true
}

// WriteSingleHoldingRegister 单个写入保持寄存器（支持多种数据类型和循环写入）
func (c *ModbusClient) WriteSingleHoldingRegister(slaveID uint8, startAddress uint16, dataType string, valueList []int32) bool {
	c.SetSlaveID(slaveID)
	byteorder, err := types.GetByteOrder(dataType)
	if err != nil {
		logx.Errorf("获取字节序失败: %v", err)
		return false
	}
	currentAddress := startAddress

	registers, err := packValuesToRegisters(byteorder, valueList)
	if err != nil {
		logx.Errorf("打包数据失败: %v", err)
		return false
	}

	for _, regValue := range registers {
		_, err := c.Client.WriteSingleRegister(currentAddress, regValue)
		if err != nil {
			logx.Errorf("写入保持寄存器时出错: %v", err)
			return false
		}
		currentAddress++
	}
	return true
}

// WriteMultipleHoldingRegisters 批量写入保持寄存器（支持多寄存器和多种数据类型）
func (c *ModbusClient) WriteMultipleHoldingRegisters(slaveID uint8, startAddress uint16, dataType string, valueList []int32) bool {
	c.SetSlaveID(slaveID)
	byteorder, err := types.GetByteOrder(dataType)
	if err != nil {
		logx.Errorf("获取字节序失败: %v", err)
		return false
	}

	registers, err := packValuesToRegisters(byteorder, valueList)
	if err != nil {
		logx.Errorf("打包数据失败: %v", err)
		return false
	}

	_, err = c.Client.WriteMultipleRegisters(startAddress, uint16(len(registers)), intsToBytes(registers))
	if err != nil {
		logx.Errorf("(16功能码)写入保持寄存器时发生异常: %v", err)
		return false
	}
	return true
}

// WriteSingleHoldingRegisterFloat 单个写入保持寄存器（支持多种数据类型和 float32 类型）
func (c *ModbusClient) WriteSingleHoldingRegisterFloat(slaveID uint8, startAddress uint16, dataType string, valueList []float32) bool {
	c.SetSlaveID(slaveID)
	byteorder, err := types.GetByteOrder(dataType)
	if err != nil {
		logx.Errorf("获取字节序失败: %v", err)
		return false
	}
	currentAddress := startAddress

	registers, err := packValuesToRegistersFloat(byteorder, valueList)
	if err != nil {
		logx.Errorf("打包数据失败: %v", err)
		return false
	}

	for _, regValue := range registers {
		_, err := c.Client.WriteSingleRegister(currentAddress, regValue)
		if err != nil {
			logx.Errorf("写入保持寄存器时出错: %v", err)
			return false
		}
		currentAddress++
	}
	return true
}

// WriteMultipleHoldingRegistersFloat 批量写入保持寄存器（支持多寄存器和 float32 类型）
func (c *ModbusClient) WriteMultipleHoldingRegistersFloat(slaveID uint8, startAddress uint16, dataType string, valueList []float32) bool {
	c.SetSlaveID(slaveID)
	byteorder, err := types.GetByteOrder(dataType)
	if err != nil {
		logx.Errorf("获取字节序失败: %v", err)
		return false
	}

	registers, err := packValuesToRegistersFloat(byteorder, valueList)
	if err != nil {
		logx.Errorf("打包数据失败: %v", err)
		return false
	}

	_, err = c.Client.WriteMultipleRegisters(startAddress, uint16(len(registers)), intsToBytes(registers))
	if err != nil {
		logx.Errorf("(16功能码)写入保持寄存器时发生异常: %v", err)
		return false
	}
	return true
}

// packValuesToRegistersFloat 将 float32 值列表根据字节序打包为寄存器值列表
func packValuesToRegistersFloat(byteorder types.ByteOrder, valueList []float32) ([]uint16, error) {
	var registers []uint16
	for _, value := range valueList {
		packed := packValue(byteorder, value)
		for i := 0; i < len(packed); i += 2 {
			if i+2 > len(packed) {
				return nil, fmt.Errorf("打包数据长度不是 2 的倍数")
			}
			chunk := packed[i : i+2]
			regValue := binary.BigEndian.Uint16(chunk)
			registers = append(registers, regValue)
		}
	}
	return registers, nil
}

// GetLatestMessage 获取最新的消息
func (c *ModbusClient) GetLatestMessage() []string {
	var messageList []string
	for !c.messageQueue.IsEmpty() {
		message := c.messageQueue.Dequeue()
		// 进行类型断言
		if msgStr, ok := message.(string); ok {
			messageList = append(messageList, msgStr)
		} else {
			// 记录类型断言失败的日志
			logx.Errorf("Failed to assert message type to string: %v", message)
		}
	}
	logx.Debugf("获取到的消息列表: %v", messageList)
	return messageList
}
